<?php
/**************************************************
* PluginLotto.com                                 *
* Copyrights (c) 2005-2010. iZAP                  *
* All rights reserved                             *
***************************************************
* @author iZAP Team "<support@izap.in>"
* @link http://www.izap.in/
* @version 1.0
* Under this agreement, No one has rights to sell this script further.
* For more information. Contact "Tarun Jangra<tarun@izap.in>"
* For discussion about corresponding plugins, visit http://www.pluginlotto.com/pg/forums/
* Follow us on http://facebook.com/PluginLotto and http://twitter.com/PluginLotto
*/
class IzapSocialAuction extends IzapObject {

  const UPLOAD_FILE_PREFIX="izap-social-auction/";
  const AUCTION_POST_FEE=1;
  const AUCTION_IMAGE_FEE=2;

  public static $fee_array;
  private static $_paypal_acc_id;

  private $_auction_image_hash;

  public function  __construct($guid=null, $params=array()) {
    parent::__construct($guid, $params);
    self::$fee_array = array(
      'AUCTION_POST_FEE' => ((get_plugin_setting('fee_auction_listing', GLOBAL_AUCTION_PLUGIN))>0 ? get_plugin_setting('fee_auction_listing', GLOBAL_AUCTION_PLUGIN) : 0),
      'AUCTION_IMAGE_FEE' => ((get_plugin_setting('fee_image_upload', GLOBAL_AUCTION_PLUGIN))>0 ? get_plugin_setting('fee_image_upload', GLOBAL_AUCTION_PLUGIN) : 0),
    );
    self::$_paypal_acc_id = get_plugin_setting('paypal_acc_id', GLOBAL_AUCTION_PLUGIN);
  }

  public function get_test_mode() {
    return get_plugin_setting('test_mode', GLOBAL_AUCTION_PLUGIN)=='y' ? true : false;
  }

  public static function get_paypal_acc_id() {
    return self::$_paypal_acc_id;
  }

  public function get_attributes_array() {
    return array(
      'title'=>array('type'=>"string",'required'=>true,'default'=>null),
      'description'=>array('type'=>"text",'required'=>true,'default'=>null),
      'tags'=>array('type'=>"tags",'required'=>false,'default'=>null),
      'expire_date'=>array('type'=>"date",'required'=>true,'default'=>null,'min'=>CURRENT_TIMESTAMP),
      'access_id'=>array('type'=>"numerical",'required'=>true,'default'=>get_default_access()),
      'terms'=>array('type'=>"string",'required'=>true,'default'=>null),
      'upl_img'=>array('type'=>"file",'required'=>false,'default'=>null),
      'base_price_n_increment' => array('type' => 'string', 'required' => TRUE, 'default' => 0),
    );
  }

  public function getIcon($size = 'medium') {
    return func_get_img_link_byizap($this, array('width'=>100, 'height'=>100));
  }

  public function getHigestBid() {
    $higest_bid = null;
    $bids_array = unserialize($this->bids);
    if(is_array($bids_array) && sizeof($bids_array)) {
      foreach($bids_array as $ownerId=>$bids) {
        foreach($bids as $bid) {
          if($bid['amount'] > $higest_bid) {
            $higest_bid = $bid['amount'];
          }
        }
      }
    }
    return ($higest_bid&&$higest_bid>$this->getBasePrice()) ? $higest_bid : $this->getBasePrice();
  }

  public function displayHighestBid() {
    $higest_bid = $this->getHigestBid();
    return ($higest_bid > $this->getBasePrice()) ? (CURRENCY_SYMBOL . $higest_bid) : "N/A";
  }

  public function getBasePrice() {
    $array = explode('/', $this->base_price_n_increment);

    return $array[0];
  }

  public function getPriceIncrement() {
    $array = explode('/', $this->base_price_n_increment);

    return ($array[1]) ? $array[1] : 1;
  }

  public function getMinimumBid() {
    return $this->getHigestBid() + $this->getPriceIncrement();
  }

  public function getItemStatus() {
    return ($this->isItemOpen()===true) ? "Open" : "Closed";
  }

  public function getRemainingTime() {
    if($this->isItemOpen()===false) {
      return 'N/A';
    }
    $end_date = $this->expire_date;
    $start_date = CURRENT_TIMESTAMP;
    
    (string)	$display_output = null;
    (string) $minute = 60;
    (string) $hour = 60 * $minute;
    (string) $day = 24 * $hour;

    $time_left = $end_date - $start_date;

    $days_left = floor($time_left/$day);

    $hours = $time_left - ($days_left * $day);
    $hours_left = floor($hours/$hour);

    $minutes = $hours - ($hours_left * $hour);
    $minutes_left = floor($minutes/$minute);

    if ($time_left > 0)
    {
      $display_output = (($days_left>0) ? $days_left . ' ' . (($days_left==1) ? "day" : "days") . ', ' : '') .
        (($hours_left>0 || $days_left>0) ? $hours_left . " hours" : '') . ' ' . $minutes_left . " minutes";
    }
    else if (!$end_date)
    {
      $display_output = "N/A";
    }
    else
    {
      $display_output = "Closed";
    }

    return $display_output;
  }

  public function getItemLocation() {
    return "N/A";
  }

  public function getStartBid() {
    return $this->getBasePrice();
  }

  public function displayStartBid() {
    return CURRENCY_SYMBOL . $this->getStartBid();
  }

  public function isItemOpen() {
    return (($this->expire_date-CURRENT_TIMESTAMP)>0 && $this->status!==0) ? true : false;
  }

  public function getHighestBidderId() {
    return $this->winner_guid;
  }

  public function endAuction() {
    if($this->is_expired==1) {
      return true;
    }
    func_hook_access_over_ride_byizap(array('status'=>true));
    if($this->expire_date > CURRENT_TIMESTAMP) {
      $this->expire_date = CURRENT_TIMESTAMP;
      //$this->access_id = ACCESS_PRIVATE;
    }
    $this->is_expired = 1;
    parent::save(false);

    // notify winner
    if($this->winner_guid) {
      $msgArr = self::get_message_to_notify('auction_won');
      notify_user($this->winner_guid, $this->site_guid, $msgArr['subject'], sprintf($msgArr['msg'], '<a href="'.$this->getURL().'">'.$this->title.'</a>') );
      $winner_name_to_notify = '<a href="'.$this->get_winner()->getURL().'">' . $this->get_winner()->name . '</a>';
    } else {
      $winner_name_to_notify = 'none';
    }

    // notify owner
    $msgArr = self::get_message_to_notify('auction_closed');
    notify_user($this->owner_guid, $this->site_guid, $msgArr['subject'], sprintf($msgArr['msg'], '<a href="'.$this->getURL().'">'.$this->title.'</a>', $winner_name_to_notify) );

    disable_entity($this->guid);
    func_hook_access_over_ride_byizap(array('status'=>false));
    return true;
  }

  public function save() {
    if($this->is_new_record()!==true) {
      $this->_auction_image_hash = md5_file($this->getFilenameOnFilestore());
      $price_bak = $this->getBasePrice();
      $highest_bid = $this->getHigestBid();
    }
    if(parent::save()) {
      $this->_setupFee();
      if($this->expire_date>$this->expire_date_bak) {
        $this->expire_date_bak = $this->expire_date;
      }
      if($this->getBasePrice()>$price_bak && $highest_bid<$this->getBasePrice()) {
        $this->winner_guid = 0;
        $this->outbidder_guid = 0;
      }
      return true;
    }
    return false;
  }

  private function _setupFee() {
    if($this->is_new_record() || true) {
      // calculate auction fee

      $auction_fee_array = array();
      if($this->is_new_record()) {
        $total_fee = 0;
      } else {
        if($this->isItemOpen()) {
          $total_fee = 0;
        } else {
          $total_fee = $this->auction_fee;
          $auction_fee_array = unserialize($this->auction_fee_array);
        }
      }
      
      // add image upload fee
      if( @file_exists($this->getFilenameOnFilestore()) && @is_file($this->getFilenameOnFilestore()) && md5_file($this->getFilenameOnFilestore())!=$this->_auction_image_hash ) {
        $amount = self::$fee_array['AUCTION_IMAGE_FEE'];
        $auction_fee_array[self::AUCTION_IMAGE_FEE] = array('type'=>"AUCTION_IMAGE_FEE", 'amount'=>$amount);
        $total_fee += $amount;
      }
      
      // add auction post duration fee
      if($this->is_new_record()) {
        $auction_duration = ceil( ($this->expire_date-CURRENT_TIMESTAMP)/(60*60*24) );
      } else {
        $auction_duration = ceil( ($this->expire_date-$this->expire_date_bak)/(60*60*24) );
      }

      if($auction_duration>0) {
        $amount = (self::$fee_array['AUCTION_POST_FEE']*$auction_duration);
        $auction_fee_array[self::AUCTION_POST_FEE] = array('type'=>"AUCTION_POST_FEE", 'amount'=>($amount+$auction_fee_array[self::AUCTION_POST_FEE]['amount']) );
        $total_fee += $amount;
      }

      $this->auction_fee = $total_fee;
      $this->auction_fee_array = serialize($auction_fee_array);

      if($total_fee > 0) {
        $this->status = 0;
        $this->access_id_original = $this->access_id;
        $this->access_id = ACCESS_PUBLIC;
      } else {
        $this->status = 1;
        $this->add_to_river('created', 'created_auction');
      }

      $this->set_is_new_record(false);
      parent::save(false);

      if($total_fee > 0) {
        disable_entity($this->guid);
      } else {
        $this->approveAuction();
      }
//
//      echo $auction_duration . '<br />';
//      func_printarray_byizap($auction_fee_array);
//      echo $this->auction_fee;
    }
  }

  public function approveAuction() {
    $entity = get_entity($this->guid);
    func_hook_access_over_ride_byizap(array('status' => true));
    $entity->expire_date = $entity->expire_date+(CURRENT_TIMESTAMP-$entity->time_created);
    $entity->status = 1;
    $entity->access_id = $entity->access_id_original;

    parent::save(false);
    $entity->add_to_river('created', 'created_auction');

    // notify owner
    $msgArr = self::get_message_to_notify('auction_enabled');
    notify_user($entity->owner_guid, $entity->site_guid, $msgArr['subject'], sprintf($msgArr['msg'], '<a href="'.$entity->getURL().'">'.$entity->title.'</a>') );

    func_hook_access_over_ride_byizap(array('status' => false));    
    return true;
  }

  public function get_auction_fee_array() {
    return unserialize($this->auction_fee_array);
  }

  public function can_edit_expire_date() {
    if($this->guid==false) {
      return true;
    }
    return ($this->expire_date>CURRENT_TIMESTAMP) ? true : false;
  }

  public function add_to_river($action, $view=null) {
    return ;
    if($view==null) {
      $view = $action;
    }
    add_to_river(
      func_get_template_path_byizap(
        array('type' => 'river')
      ) . $view,
      $action,
      $this->owner_guid,
      $this->guid
    );
  }

  public function can_edit_auction() {
    if( ($this->expire_date>CURRENT_TIMESTAMP && $this->canEdit()) || isadminloggedin() ) {
      return true;
    }
    return false;
  }

  public function is_closed_item() {
    if( $this->isItemOpen()==false && $this->winner_guid ) {
      return true;
    }
    return false;
  }

  public function get_winner() {
    return get_entity($this->winner_guid);
  }

  public function try_end_auction() {
    if($this->expire_date<CURRENT_TIMESTAMP) {
      $this->endAuction();
    }
  }

  public static function get_message_to_notify($type) {
    $returnVar = array();
    switch($type) {
      case 'auction_won':
        $returnVar ['subject'] = "Auction won";
        $returnVar ['msg'] = "Congratulations, you have won the auction named '%s'.";
        break;
      case 'auction_closed':
        $returnVar['subject'] = "Auction closed";
        $returnVar ['msg'] = "Your auction named '%s' was closed.\n The winner of this auction was %s.";
        break;
      case 'auction_enabled':
        $returnVar['subject'] = "Auction activated";
        $returnVar ['msg'] = "Congratulations, your auction named '%s' was activated.";
      default:
        break;
    }
    return $returnVar;
  }
}
